#!/usr/bin/env bash
#
# @license Apache-2.0
#
# Copyright (c) 2017 The Stdlib Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Finds files.

# shellcheck disable=SC2153


# VARIABLES #

# Determine the host kernel:
kernel=$(uname -s)

# Determine root directory:
root_dir="$(git rev-parse --show-toplevel)"

# Define the path to the build directory:
build_dir="${root_dir}/build"

# Define the folder name convention for generated files:
build_folder='build'

# Define the path to the reports directory:
reports_dir="${root_dir}/reports"

# Define the path to node modules:
node_modules="${root_dir}/node_modules"

# Define a filename pattern:
files_pattern="${FILES_PATTERN}"
if [[ -z "${files_pattern}" ]]; then
	files_pattern='*'
fi

# Define the pattern for filtering files based on their path:
files_filter="${FILES_FILTER}"
if [[ -z "${files_filter}" ]]; then
	files_filter='.*/.*'
fi


# FUNCTIONS #

# Finds files.
main() {
	local files

	# On Mac OSX, in order to use `|` and other regular expression operators, we need to use enhanced regular expression syntax (-E); see https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man7/re_format.7.html#//apple_ref/doc/man/7/re_format.
	if [[ "${kernel}" == "Darwin" ]]; then
		files=$(find -E "${root_dir}" -type f -name "${files_pattern}" -regex "${files_filter}" '!' -path "${root_dir}/.*" '!' -path "${node_modules}/*" '!' -path "${build_dir}/*" '!' -path "${reports_dir}/*" '!' -path "${root_dir}/**/${build_folder}/*")
	else
		files=$(find "${root_dir}" -regextype posix-extended -type f -name "${files_pattern}" -regex "${files_filter}" '!' -path "${root_dir}/.*" '!' -path "${node_modules}/*" '!' -path "${build_dir}/*" '!' -path "${reports_dir}/*" '!' -path "${root_dir}/**/${build_folder}/*")
	fi
	echo "${files}"
}

# Run main:
main
